from .serializers import MerchantSerializer, GoodsCategorySerializer
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from meituan.models import Merchant, GoodsCategory


@require_http_methods(['GET', 'POST'])
def merchant(request):
    if request.method == 'GET':
        queryset = Merchant.objects.all()
        ## 将所有的 merchant 序列化返回
        ## many = true 表示以 queryset 是一个 包含多个对象的列表 而不是单个对象 ,序列化器回 将每个对象都序列化成 JSON 格式
        result = MerchantSerializer(instance=queryset, many=True)
        ## safe = False 允许返回非字典类型的数据 如 列表
        return JsonResponse(result.data, status=200, safe=False)
    else:
        result = MerchantSerializer(data=request.POST)
        if result.is_valid():
            result.save()
            return JsonResponse(result.data, status=200)
        else:
            return JsonResponse(result.errors, status=400)


@require_http_methods(['GET', 'POST'])
def category(request):
    if request.method == 'GET':
        queryset = GoodsCategory.objects.all()
        result = GoodsCategorySerializer(instance=queryset, many=True)
        return JsonResponse(result.data, status=200, safe=False)
    else:
        result = GoodsCategorySerializer(data=request.POST)
        if result.is_valid():
            result.save()
            return JsonResponse(result.data, status=200)
        else:
            return JsonResponse(result.errors, status=400)
